<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { storeToRefs } from "pinia";
import {  showFailToast, showSuccessToast } from "vant";
import useConsultStore from "@/pinia/modules/consultStore.ts";
import usePatientStore from "@/pinia/modules/patientStore.ts";
import type { ConsultOrderPreParams } from "@/types/consultTypes";
import type { Patient } from "@/types/patientTypes";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import PaySheet from "@/components/lib/paySheet.vue";

const consultStore = useConsultStore();

const patientStore = usePatientStore();

const router = useRouter();

const { consultInfo, orderPre } = storeToRefs(consultStore);

/*是否显示支付方式的动作面板组件*/
const showSheet = ref<boolean>(false);

/*是否同意协议*/
const isAgree = ref<boolean>(true);

/*生成订单后的订单id*/
const orderId = ref<string>("");


/*患者信息*/
const patientInfo = ref<Patient>(<Patient>{});

/*获取订单预支付的参数*/
const orderPreParams = reactive<ConsultOrderPreParams>({
    type: consultInfo.value.type,
    illnessType: consultInfo.value.illnessType,
});

/*获取患者信息的请求函数*/
const fetchPatientInfo = async () => {
    const patient: Patient = await patientStore.findPatient(consultInfo.value.patientId as string);
    patientInfo.value = patient;
};


/*获取订单预支付的请求函数*/
const fetchOrderPre = async () => {
    try {
        await consultStore.fetchOrderPre(orderPreParams);
    } catch (error: any) {
        // router.replace("/consultRecord");
        // showFailToast("订单详情获取失败");
    }
};

/*点击立即支付按钮的回调函数(创建订单)*/
const handleSubmit = async () => {
    if (!isAgree.value) return showFailToast("请勾选协议");
    if (orderId.value) return;
    showSheet.value = true;
    try {
        orderId.value = await consultStore.createConsultOrder(consultInfo.value);
        showSuccessToast("订单生成成功");
        consultStore.clearConsultInfo();
    } catch (error: any) {
        showFailToast(error.message);
    }
};


onMounted(async () => {
    try {
        await Promise.all([fetchOrderPre(), fetchPatientInfo()]);
    } catch (error) {
        showFailToast("订单详情获取失败");
        router.replace("/consultRecord");
    }
});


/*  在导航离开渲染该组件的对应路由时调用 与 `beforeRouteUpdate` 一样，它可以访问组件实例 `this`*/
onBeforeRouteLeave(() => {
    if (orderId.value) return false;
});


</script>

<template>
    <div class="pay" v-if="orderPre.actualPayment && patientInfo.id">
        <nav-bar title="问诊支付" left-arrow left-text="返回" @click-left="$router.back()"></nav-bar>
        <div class="pay-info">
            <img class="img" src="@/assets/images/avatar-doctor.svg" />
            <p class="desc">
                <span>极速问诊——(图文问诊 {{ orderPre.actualPayment }} 元)</span>
                <span>自动分配医生</span>
            </p>
        </div>
        <van-cell-group>
            <van-cell title="优惠券" :value="`-¥${orderPre.couponDeduction}`" />
            <van-cell title="积分抵扣" :value="`-¥${orderPre.pointDeduction}`" />
            <van-cell title="实付款" :value="`¥${orderPre.actualPayment}`" class="pay-price" />
        </van-cell-group>
        <div class="pay-space"></div>
        <van-cell-group>
            <van-cell title="患者信息" :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"></van-cell>
            <van-cell title="病情描述" :value="consultInfo.illnessDesc"></van-cell>
        </van-cell-group>
        <div class="pay-schema">
            <van-checkbox v-model="isAgree">我已同意 <span class="text">支付协议</span></van-checkbox>
        </div>

        <van-submit-bar button-type="primary" :price="orderPre.actualPayment * 100" button-text="立即支付" text-align="left" @click="handleSubmit" />


        <pay-sheet pay-callback="http://localhost:80/consult/chitchat" v-model:show-sheet="showSheet" :order-id="orderId" :actual-payment="orderPre.actualPayment" @clearOrderId="orderId=''"></pay-sheet>

    </div>
</template>

<style lang="scss" scoped>
.pay {
    padding: 0 0 50px 0;

    .pay-info {
        display: flex;
        padding: 15px;
        flex-wrap: wrap;
        align-items: center;

        .tit {
            width: 100%;
            font-size: 16px;
            margin-bottom: 10px;
        }

        .img {
            margin-right: 10px;
            width: 38px;
            height: 38px;
            border-radius: 4px;
            overflow: hidden;
        }

        .desc {
            flex: 1;

            > span {
                display: block;
                color: var(--cp-tag);

                &:first-child {
                    font-size: 16px;
                    color: var(--cp-text2);
                }
            }
        }
    }

    .pay-price {
        :deep {
            .vam-cell__title {
                font-size: 16px;
            }

            .van-cell__value {
                font-size: 16px;
                color: var(--cp-price);
            }
        }
    }

    .pay-space {
        height: 12px;
        background-color: var(--cp-bg);
    }

    .pay-schema {
        height: 56px;
        display: flex;
        align-items: center;
        justify-content: center;

        .text {
            color: var(--cp-primary);
        }
    }

    :deep {
        .van-submit-bar__button {
            font-weight: normal;
            width: 160px;
        }
    }

    .pay-type {
        .amount {
            padding: 20px;
            text-align: center;
            font-size: 16px;
            font-weight: bold;
        }

        .btn {
            padding: 15px;
        }

        .van-cell {
            align-items: center;

            .cp-icon {
                margin-right: 10px;
                font-size: 18px;
            }

            .van-checkbox :deep(.van-checkbox__icon) {
                font-size: 16px;
            }
        }
    }
}

</style>
